package com.ruoyi.basic.controller;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.ruoyi.api.system.utils.ShiroUtils;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.service.IBasicUserService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.basic.domain.BasicImage;
import com.ruoyi.basic.service.IBasicImageService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * 员工图片Controller
 * 
 * @author ruoyi
 * @date 2021-12-07
 */
@Controller
@RequestMapping("/basic/image")
public class BasicImageController extends BaseController
{
    private String prefix = "basic/image";

    @Autowired
    private IBasicImageService basicImageService;

    @Autowired
    private IBasicUserService basicUserService;

    @RequiresPermissions("basic:image:view")
    @GetMapping()
    public String image()
    {
        return prefix + "/image";
    }

    /**
     * 查询员工图片列表
     */
    @RequiresPermissions("basic:image:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BasicImage basicImage)
    {
        startPage();
        List<BasicImage> list = basicImageService.selectBasicImageList(basicImage);
        return getDataTable(list);
    }

    /**
     * 新增员工图片
     */
    @GetMapping("/add/{userId}")
    public String add(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        BasicUser user = basicUserService.selectBasicUserById(userId);
        mmap.put("user", user == null ? new BasicUser() : user);
        return prefix + "/add";
    }

    /**
     * 新增保存员工图片
     */
    @RequiresPermissions("basic:image:add")
    @Log(title = "员工图片", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("files") MultipartFile[] files, BasicImage basicImage) throws IOException {
        BasicUser basicUser = basicUserService.selectBasicUserById(basicImage.getUserId());
        for(MultipartFile file : files){
            if(!file.isEmpty()) {
                boolean flag = basicImageService.checkBasicImageByFileName(file.getOriginalFilename(), basicImage);
                String imageFile = FileUploadUtils.upload(RuoYiConfig.getUploadPath() + "/" + basicUser.getName(), file, flag);
                basicImage.setImageFile(imageFile);
                basicImage.setCreateBy(ShiroUtils.getLoginName());
                basicImageService.insertBasicImage(basicImage);
            }
        }
        return success();
    }

    /**
     * 修改员工图片
     */
    @GetMapping("/edit/{imageId}")
    public String edit(@PathVariable("imageId") Long imageId, ModelMap mmap)
    {
        BasicImage basicImage = basicImageService.selectBasicImageByImageId(imageId);
        mmap.put("basicImage", basicImage);
        String filePath = RuoYiConfig.getProfile() + StringUtils.substringAfter(basicImage.getImageFile(), Constants.RESOURCE_PREFIX);
        String imageContent = "data:image/files;base64," + ImageUtils.imageToBase64(filePath);
        mmap.put("imageContent", imageContent);
        return prefix + "/edit";
    }

    /**
     * 修改保存员工图片
     */
    @RequiresPermissions("basic:image:edit")
    @Log(title = "员工图片", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam(required = false) MultipartFile file, BasicImage basicImage)
    {
        try {
            BasicUser basicUser = basicUserService.selectBasicUserById(basicImage.getUserId());
            if(!file.isEmpty()) {
                BasicImage old = basicImageService.selectBasicImageByImageId(basicImage.getImageId());
                FileUtils.deleteFile(RuoYiConfig.getProfile() + StringUtils.substringAfter(old.getImageFile(), Constants.RESOURCE_PREFIX));

                boolean flag = basicImageService.checkBasicImageByFileName(file.getOriginalFilename(), basicImage);
                String imageFile = FileUploadUtils.upload(RuoYiConfig.getUploadPath() + "/" + basicUser.getName(), file, flag);
                basicImage.setImageFile(imageFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return error("图片上传失败");
        }
        basicImage.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(basicImageService.updateBasicImage(basicImage));
    }

    /**
     * 删除员工图片
     */
    @RequiresPermissions("basic:image:remove")
    @Log(title = "员工图片", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        for(Long id : Convert.toLongArray(ids)){
            BasicImage basicImage = basicImageService.selectBasicImageByImageId(id);
            FileUtils.deleteFile(RuoYiConfig.getProfile() + StringUtils.substringAfter(basicImage.getImageFile(), Constants.RESOURCE_PREFIX));
        }
        return toAjax(basicImageService.deleteBasicImageByImageIds(ids));
    }

    /**
     * 导出员工图片
     */
    @RequiresPermissions("basic:image:download")
    @Log(title = "员工图片", businessType = BusinessType.EXPORT)
    @GetMapping( "/download/{userId}")
    public void download(@PathVariable("userId") Long userId, HttpServletResponse response) throws Exception
    {
        List<BasicImage> imageList = basicImageService.selectBasicImageListByUserId(userId);
        String strZipPath = RuoYiConfig.getDownloadPath() + System.currentTimeMillis() + ".zip";
        ZipOutputStream out = null;
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try{
            out = new ZipOutputStream(new FileOutputStream(strZipPath));
            ServletOutputStream outputStream = response.getOutputStream();
            for(BasicImage basicImage : imageList) {
                String downloadPath = RuoYiConfig.getProfile() + StringUtils.substringAfter(basicImage.getImageFile(), Constants.RESOURCE_PREFIX);
                // 下载名称
                String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
                out.putNextEntry(new ZipEntry(downloadName));
                File file = new File(downloadPath);
                if(file.exists()) {
                    fis = new FileInputStream(file);
                    byte[] b = new byte[1024];
                    int length;
                    while ((length = fis.read(b)) > 0) {
                        out.write(b, 0, length);
                    }
                    out.closeEntry();
                }
            }
            out.close();
            bis = new BufferedInputStream(new FileInputStream(strZipPath));
            FileCopyUtils.copy(bis, outputStream);
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            IOUtils.close(bis);
            IOUtils.close(fis);
            IOUtils.close(out);
        }
        FileUtils.deleteFile(strZipPath);
    }

    /**
     * 导出员工图片
     */
    @RequiresPermissions("basic:image:download")
    @Log(title = "员工图片", businessType = BusinessType.EXPORT)
    @GetMapping( "/download")
    public void download(String imageIds, HttpServletResponse response) throws Exception
    {
        List<BasicImage> imageList = basicImageService.selectBasicImageListByImageIds(imageIds);
        String strZipPath = RuoYiConfig.getDownloadPath() + System.currentTimeMillis() + ".zip";
        ZipOutputStream out = null;
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try{
            out = new ZipOutputStream(new FileOutputStream(strZipPath));
            ServletOutputStream outputStream = response.getOutputStream();
            for(BasicImage basicImage : imageList) {
                String downloadPath = RuoYiConfig.getProfile() + StringUtils.substringAfter(basicImage.getImageFile(), Constants.RESOURCE_PREFIX);
                // 下载名称
                String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
                out.putNextEntry(new ZipEntry(downloadName));
                File file = new File(downloadPath);
                if(file.exists()) {
                    fis = new FileInputStream(file);
                    byte[] b = new byte[1024];
                    int length;
                    while ((length = fis.read(b)) > 0) {
                        out.write(b, 0, length);
                    }
                    out.closeEntry();
                }
            }
            out.close();
            bis = new BufferedInputStream(new FileInputStream(strZipPath));
            FileCopyUtils.copy(bis, outputStream);
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            IOUtils.close(bis);
            IOUtils.close(fis);
            IOUtils.close(out);
        }
        FileUtils.deleteFile(strZipPath);
    }
}
